<template>
  <div id="globalSider">
    <a-layout-sider
      v-if="loginUserStore.loginUser.id"
      width="200"
      breakpoint="lg"
      collapsed-width="0"
    >
      <a-menu
        v-model:selectedKeys="current"
        mode="inline"
        :items="menuItems"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref, watchEffect } from 'vue'
import { PictureOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { SPACE_TYPE_ENUM } from '@/constants/space.ts'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController.ts'
import { message } from 'ant-design-vue'

const loginUserStore = useLoginUserStore()
const router = useRouter()

// 固定的基础菜单（不包含创建团队）
const baseFixedMenuItems = [
  {
    key: '/',
    icon: () => h(PictureOutlined),
    label: '公共图库',
  },
  {
    key: '/my_space',
    label: '我的空间',
    icon: () => h(UserOutlined),
  },
]

// 创建团队菜单（动态控制显示）
const createTeamMenuItem = {
  key: '/add_space?type=' + SPACE_TYPE_ENUM.TEAM,
  label: '创建团队',
  icon: () => h(TeamOutlined),
}

const teamSpaceList = ref<API.SpaceUserVO[]>([])

// 计算是否已有团队
const hasTeam = computed(() => {
  return teamSpaceList.value.some(spaceUser =>
    spaceUser.spaceId && spaceUser.space?.spaceName
  )
})

// 动态构建菜单
const menuItems = computed(() => {
  // 过滤有效团队空间
  const validTeamSpaces = teamSpaceList.value.filter(spaceUser =>
    spaceUser.spaceId && spaceUser.space?.spaceName
  )

  // 基础菜单列表
  const baseMenuItems = [...baseFixedMenuItems]

  // 如果没有团队，显示创建团队按钮
  if (!hasTeam.value) {
    baseMenuItems.push(createTeamMenuItem)
  }

  // 如果有有效团队空间，显示团队分组
  if (validTeamSpaces.length > 0) {
    const teamSpaceSubMenus = validTeamSpaces.map((spaceUser) => ({
      key: '/space/' + spaceUser.spaceId,
      label: spaceUser.space?.spaceName,
    }))

    const teamSpaceMenuGroup = {
      type: 'group',
      label: '我的团队',
      key: 'teamSpace',
      children: teamSpaceSubMenus,
    }

    baseMenuItems.push(teamSpaceMenuGroup)
  }

  return baseMenuItems
})

// 加载团队空间列表
const fetchTeamSpaceList = async () => {
  try {
    const res = await listMyTeamSpaceUsingPost()
    if (res.data.code === 0) {
      // 确保是数组类型
      teamSpaceList.value = res.data.data || []
    } else {
      message.error('加载我的团队空间失败：' + (res.data.message || '未知错误'))
      teamSpaceList.value = []
    }
  } catch (error) {
    message.error('加载团队空间时发生错误')
    console.error(error)
    teamSpaceList.value = []
  }
}

/**
 * 监听登录状态和路由变化，重新加载数据
 */
watchEffect(() => {
  if (loginUserStore.loginUser.id) {
    fetchTeamSpaceList()
  } else {
    teamSpaceList.value = []
  }
})

// 监听路由变化，当从创建团队页面返回时刷新列表
router.afterEach((to, from) => {
  // 当从创建团队页面跳转回来时，重新加载团队列表
  if (from.path === '/add_space' && from.query.type === SPACE_TYPE_ENUM.TEAM) {
    fetchTeamSpaceList()
  }
  current.value = [to.path]
})

// 当前要高亮的菜单项
const current = ref<string[]>([])

// 路由跳转事件
const doMenuClick = ({ key }) => {
  router.push(key)
}
</script>

<style scoped>
#globalSider .ant-layout-sider {
  background: none;
}

/* 确保空菜单组不会占用空间 */
.ant-menu-group-title:empty {
  display: none;
}

.ant-menu-item-group.ant-menu-item-group-empty {
  display: none;
}
</style>
